package com.swordxu.yim.server.msgcoder;

import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.List;

/**
 * 客户端消息编码类
 * Created by user063 on 2014/12/26.
 */
public class ClientMessageEncoder extends MessageToMessageEncoder<CharSequence> {
    private final Charset charset;

    /**
     * 构造函数
     */
    public ClientMessageEncoder() {
        this(Charset.defaultCharset());
    }

    public ClientMessageEncoder(Charset charset) {
        if (charset == null) {
            throw new NullPointerException("charset");
        }
        this.charset = charset;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, CharSequence msg, List<Object> out) throws Exception {
        //消息为空
        if (msg.length() == 0) {
            return;
        }
        ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(msg), charset);

    }
}
